# -*- coding: utf-8 -*-
import webapp2
from google.appengine.api import users 
from google.appengine.ext import db
import os
import jinja2
import datetime

jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
                                       autoescape=True)

class UserTable(db.Model):
    useremail = db.Key()
    nickname = db.StringProperty() # derived from useremail
##    admin = db.BooleanProperty()
    userid = db.StringProperty()
     

class ItemList(db.Model):
    itemid = db.Key()
    itemname = db.StringProperty()
    itemdescription = db.StringProperty()
    itemprice = db.StringProperty()
    itemcreationtime = db.StringProperty()
    itemexpirydate = db.StringProperty()
    itemowner = db.StringProperty()
    
class MessageList(db.Model):
    messageid = db.Key()
    datesent = db.DateProperty()
    content = db.StringProperty()

class SenderTable(db.Model):  #(compound key)
    messageid = db.ReferenceProperty(MessageList, required=True, collection_name='SenderTable_messageid_set')
    senderid = db.ReferenceProperty(UserTable, required=True, collection_name='SenderTable_senderid_set')

class RecipientTable(db.Model): # (compound key)
    messageid = db.ReferenceProperty(MessageList, required=True, collection_name='RecipientTable_messageid_set') 
    recipientid = db.ReferenceProperty(UserTable, required=True, collection_name='RecipientTable_senderid_set')



class MainHandler(webapp2.RequestHandler):
    '''Home page handler'''
    def get(self):
        user = users.get_current_user()
##        useremail = user.email()

        if user: 
        # if logged in
        # display 'welcome, username' at top right hand corner
        # get username from email (key) using GQL
        
            

            UserTable(key_name=user.email(), nickname=user.email(), userid=user.user_id()).put()

            template_values = {
                'user': user,
                'logout': 'Logout',
                'logout_url': users.create_login_url(self.request.uri)
                }
               
        else:
        # if not logged in
        # display welcome guest | sign in
            user = 'guest'
            template_values = {
                'user': user,
                'login': 'Login',
                'login_url': users.create_login_url(self.request.uri)
##                'register': 'Register'
##                'register_url':
                }
        items = db.GqlQuery('''SELECT * FROM ItemList''')

        ictime = []
        idescription = []
        iedate = []
        iname = []
        iprice = []
        for item in items:
            ictime.append(item.itemcreationtime)
            idescription.append(item.itemdescription)
            iedate.append(item.itemexpirydate)
            iname.append(item.itemname)
            iprice.append(item.itemprice)

        template_values = {
            'user': user,
            'items': items,
            'ictime': ictime,
            'idescription': idescription,
            'iedate': iedate,
            'iname': iname,
            'iprice': iprice
            }


        template = jinja_environment.get_template('index.html')
        self.response.out.write(template.render(template_values))



    # regardless of whether logged in or not
    # display home page - search bar + items


class Shop(webapp2.RequestHandler):
    '''Shop handler'''
    def get(self):
        user = users.get_current_user()
##        useremail = user.email()

        if user: 
        # if logged in
        # display 'welcome, username' at top right hand corner
        # get username from email (key) using GQL

            UserTable(key_name=user.email(), nickname=user.email(), userid = user.user_id()).put()
            
        else:
        # if not logged in
        # display register | sign in
        
            self.redirect(users.create_login_url(self.request.uri))
            
        template_values = {
            'user': user,
            'logout': 'Logout',
            'logout_url': users.create_logout_url(self.request.uri)
            }

        template = jinja_environment.get_template('shop.html')
        self.response.out.write(template.render(template_values))


class SellItemPage(webapp2.RequestHandler):
    '''Sell Item page handler'''
    def get(self):
        user = users.get_current_user()
        if user: 
        # if logged in
        # display 'welcome, username' at top right hand corner
        # get username from email (key) using GQL

            UserTable(key_name=user.email(), nickname=user.email(), userid = user.user_id()).put()
            
        # if not logged in
        # display register | sign in           
        else:
            self.redirect(users.create_login_url(self.request.uri))
            
        template_values = {
           'user': user,
           'logout': 'Logout',
           'logout_url': users.create_logout_url(self.request.uri),
           'price_error_message': '',
           'name_error_message': '',
           'des_error_message': ''
           }

        template = jinja_environment.get_template('sell_item_page.html')
        self.response.out.write(template.render(template_values))		

def vprice(price):
# check for float
    try:
        float(price)
        return True

    except ValueError:
        return False

def vname(name):
	# name must be maximum 50 characters
    chars = len(name)
    if chars <= 30:
        return True
    else:
        return False
		
def vdes(description):
    chars = len(description)
    if chars <= 200:
        return True
    else:
        return False
			

class ValidateSellItem(webapp2.RequestHandler):
    ''' Validate sell items fields '''
    def post(self):
        user = users.get_current_user()
        if user:
            
            itemname = self.request.get('itemname')
            itemdescription = self.request.get('itemdescription')
            itemprice = self.request.get('itemprice')

            if vname(itemname) == False:
                name_error_msg = "Please enter an item name less than 30 characters."

            else:
                name_error_msg = ''

            if vdes(itemdescription) == False:
                des_error_msg = "Please enter a description with less than 50 words."
                
            else:
                des_error_msg = ''                    

            if vprice(itemprice) == False:
                price_error_msg = "Please enter a number for the price."
            else:
                price_error_msg = ''

                
            if vprice(itemprice) == True and  vname(itemname) == True and vdes(itemdescription) == True:
                success = 'Item successfully created.'
                itemprice="{0:.2f}".format(float(itemprice))
                itemcreationtime = datetime.datetime.now().strftime("%H:%M %p")
                today = datetime.datetime.today()
                itemcreation = str(today) + itemcreationtime
                expiration_time = datetime.timedelta(days=30)
                expiry_date = str(today + expiration_time)
##                self.response.out.write(expiry_date[0:10])
                expiry_date = expiry_date[0:10]
                #insert into item database
                ItemList(itemname=itemname,
                         itemdescription=itemdescription,
                         itemprice=itemprice,
                         itemcreationtime=itemcreationtime,
                         itemexpirydate=expiry_date,
                         itemowner=user.email()).put()
                
            else:
                success = 'Failed to upload item.'

        else:
            self.redirect(users.create_login_url(self.request.uri))

        template_values = {
            'user': user,
            'logout': 'Logout',
            'logout_url': users.create_logout_url(self.request.uri),
            'itemname': itemname,
            'itemdescription': itemdescription,
            'itemprice': itemprice,
            'price_error_message': price_error_msg,
            'name_error_message': name_error_msg,
            'des_error_message': des_error_msg,
            'success': success
           }
			
		
        template = jinja_environment.get_template('validatesellitem.html')
        self.response.out.write(template.render(template_values))



class ShopItemsPage(webapp2.RequestHandler):
    '''show shop items in rows handler'''
    def get(self):
        user = users.get_current_user()
        if user: 
        # if logged in
        # display 'welcome, username' at top right hand corner
        # get username from email (key) using GQL

            UserTable(key_name=user.email(), nickname=user.email(), userid = user.user_id()).put()

##            user_shop_items = db.GqlQuery("SELECT * FROM ItemList WHERE item_owner = :1", user.email()).fetch(10)
##        
##            self.response.out.write(user_shop_items)
   
            items = db.GqlQuery('''SELECT * FROM ItemList
                                WHERE itemowner = :1''', user.email()).fetch(100)

##            items = db.GqlQuery("SELECT * FROM ItemList")
##            items.fetch(100)
            ictime = []
            idescription = []
            iedate = []
            iname = []
            iprice = []
##            for item in items:
##                ictime.append(item.itemcreationtime)
##                idescription.append(item.itemdescription)
##                iedate.append(item.itemexpirydate)
##                iname.append(item.itemname)
##                iprice.append(item.itemprice)
##                

            

        # if not logged in
        # display register | sign in           
        else:
            self.redirect(users.create_login_url(self.request.uri))

        
                
        template_values = {
           'user': user,
           'logout': 'Logout',
           'logout_url': users.create_logout_url(self.request.uri),
           'items': items,
           'ictime': ictime,
           'idescription': idescription,
           'iedate': iedate,
           'iname': iname,
           'iprice': iprice
           }

        template = jinja_environment.get_template('shop_items_page.html')
        self.response.out.write(template.render(template_values))



class SearchItems(webapp2.RequestHandler):
    '''show shop items in rows handler'''
    def get(self):
        user = users.get_current_user()
        if user: 
        # if logged in
        # display 'welcome, username' at top right hand corner
        # get username from email (key) using GQL

            UserTable(key_name=user.email(), nickname=user.email()).put()

            search = self.request.get('search')
##            self.response.out.write(search)

##            items = db.GqlQuery('''SELECT * FROM ItemList
##                                WHERE itemowner >= '%s'
##                                AND < :1″, u’'%s'’ + u’\ufffd’''',(search))

            items = db.GqlQuery('''SELECT * FROM ItemList
                                WHERE itemname >= %s AND < :1''',
                                u'%s' + u'\ufffd''',%(search)).fetch(50)
##
##            items = db.GqlQuery('''SELECT * FROM ItemList
##                                WHERE itemname >= :1''',
##                                search).fetch(50)

            ictime = []
            idescription = []
            iedate = []
            iname = []
            iprice = []
            for item in items:
                ictime.append(item.itemcreationtime)
                idescription.append(item.itemdescription)
                iedate.append(item.itemexpirydate)
                iname.append(item.itemname)
                iprice.append(item.itemprice)
                

            

        # if not logged in
        # display register | sign in           
        else:
            self.redirect(users.create_login_url(self.request.uri))

        
                
        template_values = {
           'user': user,
           'logout': 'Logout',
           'logout_url': users.create_logout_url(self.request.uri),
           'items': items,
           'ictime': ictime,
           'idescription': idescription,
           'iedate': iedate,
           'iname': iname,
           'iprice': iprice,
           'search': search
           }

        template = jinja_environment.get_template('search_items.html')
        self.response.out.write(template.render(template_values))




class Admin(webapp2.RequestHandler):
    '''Sell Item page handler'''
    def get(self):
        user = users.get_current_user()
##        if user: 
        # if logged in
        # display 'welcome, username' at top right hand corner
        # get username from email (key) using GQL

##            UserTable(key_name=user.email(), admin=admin).put()
##        delete = user.get_by_key_name(user.email()).delete()

             # if not logged in
        # display register | sign in           
        if not user:
            self.redirect(users.create_login_url(self.request.uri))
            
        template_values = {
           'user': user,
           'logout': 'Logout',
           'logout_url': users.create_logout_url(self.request.uri),
##           'delete': delete
           }


        template = jinja_environment.get_template('admin.html')
        self.response.out.write(template.render(template_values))
		

class DeleteProfile(webapp2.RequestHandler):
    def get(self):
        user = users.get_current_user()

        if user:
            UserTable.get_by_key_name(user.email()).delete()
            # delete items owned by owner
            items = db.GqlQuery('''DELETE * FROM ItemList WHERE itemowner=:1''', user.email()).fetch(100)

            
            self.redirect('/')

class ProfilePage(webapp2.RequestHandler):
    def get(self):
        user = users.get_current_user()
        profileowner = UserTable.get_by_key_name(user.email())        

        if user:
            UserTable(key_name=user.email(), nickname=user.email(), userid=user.user_id()).put()
            
        # if not logged in
        # display register | sign in           
        else:
            self.redirect(users.create_login_url(self.request.uri))

        if profileowner:
            self.render('profile.html')
            
        template_values = {
           'user': user,
           'logout': 'Logout',
           'logout_url': users.create_logout_url(self.request.uri)
           }
        template = jinja_environment.get_template('profile.html')
        self.response.out.write(template.render(template_values))

app = webapp2.WSGIApplication([('/', MainHandler),
                               ('/shop', Shop),
                               ('/admin', Admin),
                               ('/sell_item_page', SellItemPage),
                               ('/shop_items_page' , ShopItemsPage),
                               ('/searchitems',SearchItems),
                               ('/validatesellitem', ValidateSellItem),
                               (r'/profile/(.+)', ProfilePage),
                               ('/deleteprofile', DeleteProfile),
                               ],
                              debug=True)


